<template>
  <el-main>
    <el-form :model="params" ref="searchForm" size="small">
      <el-button v-if="userType == '2'" type="primary" @click="addIntroduction">新建</el-button>
    </el-form>


    <el-table :data="tableList" class="tableAuto" empty-text="暂无数据" size="small" :height="tableHeight"
      table-layout="auto" border fit stripe>
      <el-table-column prop="name" label="实验名称"> </el-table-column>
      <el-table-column prop="className" v-if="userType == '2'" label="所属班级"></el-table-column>
      <!-- <el-table-column prop="pictures" label="实验图片">
        <img v-if="pictures" :src="http://localhost:8080/common/download?name=" class="avatar">
      </el-table-column> -->
      <el-table-column prop="pictureList" label="实验结果图片" align="center">
        <template slot-scope="{ row }">
          <el-image v-for="item in row.pictureList" style="width: auto; height: 40px; border:none;cursor: pointer;"
            :src="getImage(item)" :preview-src-list="[`http://localhost:8080/common/download?name=${item}`]">
            <!-- <div slot="error" class="image-slot">
              <img src="./../../images/noImg.png"  style="width: auto; height: 40px; border:none;" >  
            </div>   -->
          </el-image>
        </template>
        <!-- <el-button type="primary" size="small" icon="el-icon-edit" align="right" @click="editIntroduction(scope.row)">添加图片</el-button> -->
      </el-table-column>
      <el-table-column label="操作" v-if="userType == '2'" width="200">
        <template slot-scope="scope">
          <el-button type="primary" size="small" icon="el-icon-edit" @click="editIntroduction(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" icon="el-icon-delete"
            @click="deleteIntroduction(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>


    <sys-dialog :title="dialog.title" :visible="dialog.visible" :width="dialog.width" :height="dialog.height"
      @onClose="onClose" @onConfirm="onConfirm">
      <div slot="content">
        <el-form :model="addContent" ref="addForm" :rules="rules" label-width="80px" :inline="false" size="small">
          <el-form-item prop="name" label="实验名称">
            <el-input v-model="addContent.name"></el-input>
          </el-form-item>
          <el-form-item prop="className" label="班级名称">
            <el-select v-model="addContent.classId" placeholder="请选择">
              <el-option v-for="item in options" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="pictures" label="实验结果图片">
            <!-- <el-upload class="avatar-uploader" action="http://localhost:8080/common/upload" :show-file-list="false"
                :on-success="handleAvatarSuccess" :before-upload="beforeUpload" ref="upload">
                <img v-if="imageUrl" :src="imageUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload> -->
            <el-upload class="upload-demo" action="http://localhost:8080/common/upload" :on-preview="handlePreview"
              :on-remove="handleRemove" :on-success="handleAvatarSuccess" :before-remove="beforeRemove" multiple
              :limit="10" :on-exceed="handleExceed" :file-list="fileList">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
            <!-- <el-input type="textarea" v-model="addContent.pictures" :rows="5"></el-input> -->
          </el-form-item>
        </el-form>
      </div>
    </sys-dialog>
  </el-main>
</template>

<script>
import {
  getImageDisplayApi,
  updateImageDisplayApi,
  addImageDisplayApi,
  getClassListApi,
  deleteImageDisplayApi
} from "@/api/imageDisplay";
import SysDialog from "@/components/System/SysDialog.vue";
export default {
  name: "ImageDisplay",
  components: {
    SysDialog,
  },
  data() {
    return {
      fileList: [],
      tableList: [],
      pictureList: [],
      addContent: {
        id: 0,
        tno: 0,
        classId: 0,
        name: "",
        className: "",
        pictureList: '',
        pictures: "",
      },
      imageUrl: "",
      imageUrl2: "",
      params: {
        total: 0,
      },
      dialog: {
        title: "",
        visible: false,
        width: 550,
        height: 320,
      },
      options: [],
      tableHeight: 0,
      rules: {
        name: [
          {
            required: blur,
            trigger: "change",
            message: "请输入实验名称!",
          },
        ],
      },
    };
  },
  created() {
    this.getList();
    this.userType = localStorage.getItem("type");
  },
  mounted() {
    this.$nextTick(() => {
      this.tableHeight = window.innerHeight - 200;
    });
    this.getList()
  },

  methods: {
    async getList() {
      // 获取班级
      getClassListApi().then((res) => {
        this.options = res.data;
        // console.log(res);
        // console.log(this.options);
      })
      //获取实验列表

      var res = await getImageDisplayApi(this.params);
      var success = res.success

      if (success) {
        this.tableList = res.data;
        // this.pictureList = res.data.pictureList;
        this.params.total = res.data.total;
      }
    },
    handleRemove(file, fileList) {
       //从后往前删且得留一个
       if (this.addContent.typeNo == "0") {
        console.log(file.response.data);
        let len = file.response.data.length;
        this.addContent.pictures = this.addContent.pictures.substring(0, this.addContent.pictures.length - len - 1)
      }else{
        console.log(file);
        let lenn = file.name.length;
        this.addContent.pictures = this.addContent.pictures.substring(0, this.addContent.pictures.length - lenn - 1)
      }
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 10 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    //新增
    addIntroduction() {
      this.fileList = [];
      this.$resetForm("addForm", this.addContent);
      this.addContent.typeNo = "0";
      this.dialog.title = "新增仪器介绍";
      this.dialog.visible = true;
    },
    // 编辑
    editIntroduction(row) {
      this.dialog.title = "编辑仪器介绍";
      //清空表单数据
      this.$resetForm("addForm", this.addContent);
      this.addContent.typeNo = "1";

      this.fileList = [];
      let _params = 'http://localhost:8080/common/download?name=';
      for (const item in row.pictureList) {
        console.log(item);
        console.log(row.pictureList[item]);
        _params += `${row.pictureList[item]}/`
        this.fileList[item] = {
          name: `${row.pictureList[item]}`,
          url: _params
        }
      }
      // this.imageUrl = `http://localhost:8080/common/download?name=${row.pictures}`
      // this.imageUrl2 = `http://localhost:8080/common/download?name=${row.internalStructure}`
      // 编辑回显
      this.$objCoppy(row, this.addContent);
      this.dialog.visible = true;
    },
    // 删除
    async deleteIntroduction(row) {
      let confirm = await this.$myconfirm("确定删除该实验介绍吗？");
      if (confirm) {
        let res = await deleteImageDisplayApi({ id: row.id });
        //删除成功，刷新列表
        if (res.success) {
          this.getList();
          this.$message.success(res.msg);
        }
      }
    },
    //确认对话框
    onConfirm() {
      this.$refs.addForm.validate(async (valied) => {
        if (valied) {
          var res = null;
          if (this.addContent.typeNo == "0") {
            console.log(this.addContent);
            res = await addImageDisplayApi(this.addContent);
          } else {
            console.log(this.addContent);
            res = await updateImageDisplayApi(this.addContent);
          }
          if (res.success) {
            //请求成功 刷新列表
            this.getList();
            this.dialog.visible = false;
            this.$message.success(res.msg);
          }
        }
      });
    },
    getImage(image) {
      console.log(image);
      return `http://localhost:8080/common/download?name=${image}`
    },
    handleAvatarSuccess(response, file, fileList) {
      if (this.addContent.pictures == "") {
        this.addContent.pictures = response.data
      } else {
        this.addContent.pictures = this.addContent.pictures + "," + response.data
      }

      this.imageUrl = `http://localhost:8080/common/download?name=${response.data}`
    },
    beforeUpload(file) {
      if (file) {
        const suffix = file.name.split('.')[1]
        const size = file.size / 1024 / 1024 < 2
        if (['png', 'jpeg', 'jpg'].indexOf(suffix) < 0) {
          this.$message.error('上传图片只支持 png、jpeg、jpg 格式！')
          this.$refs.upload.clearFiles()
          return false
        }

        if (!size) {
          this.$message.error('上传文件大小不能超过 2MB!')
          return false
        }
        return file
      }
    },
    //关闭对话框
    onClose() {
      this.dialog.visible = false;
    },
    //页容量改变时触发
    sizeChange(val) {
      this.params.pageSize = val;
      this.getList();
    },
    //当前页数改变时触发
    currentChange(val) {
      this.params.currentPage = val;
      this.getList();
    },
    // 搜索
    searchUser() {
      this.getList();
    },
    // 重置表格
    resetUser() {
      this.params.name = "";
      this.params.phoneNumber = "";
      this.params.idCard = "";
      this.getList();
    },
  },
};
</script>

<style></style>